<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./lib/vue.js"></script>
    <script src="./lib/lodash.js"></script>
    <style>
        *{
            padding:0;
            margin:0;
        }
        #app .wrap{
            position:relative;
            margin:100px auto;
            width:300px;
            border:1px solid red;
            overflow-y: scroll;
        }
        #app .wrap .list{
            position: absolute;
            top:0;
            left:0;
            height: 300px;
        }
        #app .wrap .list p{
            line-height: 30px;
        }
        #app .wrap .scrollBar {
            background: green;
        }

    </style>
</head>
<body>
    <div id="app">
        <div ref="wrap" class="wrap" @scroll="scrollHandler">
            <h3 v-if="isLoading">正在拼命加载中……</h3>
            <template v-else>
                <div ref="list" class="list">
                    <p v-for="item in scrollList" :key="item.id">{{item.id}}-{{item.title}}</p>
                </div>
                <div ref="scrollBar" class="scrollBar"></div>
            </template>

        </div>
    </div>
</body>
<script>
    new Vue({
        el:"#app",
        data:{
            list:[],
            // 显示多少条
            num:10,
            // 每条高度
            numH:30,
            start:0,
            isLoading:true
        },
        methods:{
            // scrollHandler(){
            //     const scrollTop =  this.$refs.wrap.scrollTop;
            //     this.$refs.list.style.top = scrollTop+"px";
            //     this.start = Math.floor(scrollTop/this.numH);
            // }
            scrollHandler:_.throttle(function(){
                console.log(1111)
                const scrollTop =  this.$refs.wrap.scrollTop;
                this.$refs.list.style.top = scrollTop+"px";
                this.start = Math.floor(scrollTop/this.numH);
            },100,{
                leading:false
            })
        },
        computed:{
            scrollList(){
                return this.list.slice(this.start,this.start+10);
            }
        },
        mounted(){
            this.$refs.wrap.style.height = (this.num*this.numH)+"px";
            setTimeout(()=>{
                let result = []
                const total = 99999;
                for(let id=0;id<total;id++){
                    result.push({
                        id,
                        title:"虚拟滚动列表"
                    })
                }
                this.list = result;
                this.isLoading = false;
                this.$nextTick().then(value=>{
                    this.$refs.scrollBar.style.height = (total*this.numH)+"px";
                })

            },2000)


        }
    })
</script>
</html>